import json
import datetime

from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status

from study.models import *
from user.models import *
from user.serializer import *
from clbum.serializer import ClasssSer
from study.serializer import *
from utils.jwt_token import check_login


# 标签
class TagView(ViewSet):

    # 新增标签
    @check_login
    def add_tag(self, request):
        user_id = self._cuser.id
        name = request.data.get("name")

        print(user_id, name)

        try:

            tag = TagModel.objects.filter(name=name, user_id=user_id, is_delete=False).first()
            if tag:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "标签名称已经存在"})
            data = {
                "name": name,
                "user": user_id
            }
            ser = TagSer(data=data)
            if not ser.is_valid():
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': ser.errors})
            ser.save()
            return Response({"code": status.HTTP_200_OK, "msg": "成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 获取标签
    @check_login
    def list_tag(self, request):
        user_id = self._cuser.id
        try:
            tag_list = TagModel.objects.filter(user_id=user_id, is_delete=False).all()
            ser = TagSer(tag_list, many=TagSer)
            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": ser.data})

        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 修改标签
    @check_login
    def up_tag(self, request, pk):
        name = request.data.get("name")
        try:
            tag_list = TagModel.objects.filter(id=pk, is_delete=False)
            if not tag_list:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '没有此标签'})

            tag_list = TagModel.objects.filter(name=name, is_delete=False)
            if tag_list:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '此名称已经存在'})

            tag_list.update(name=name)
            return Response({"code": status.HTTP_200_OK, "msg": "修改成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 删除标签
    @check_login
    def del_tag(self, request, pk):
        try:
            tag_list = TagModel.objects.filter(id=pk, is_delete=False)
            if not tag_list:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '没有此标签'})
            tag_list.update(is_delete=True)
            return Response({"code": status.HTTP_200_OK, "msg": "删除成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 获取单个标签
    @check_login
    def one_tag(self, request, pk):
        try:
            tag_list = TagModel.objects.filter(id=pk, is_delete=False).first()
            if not tag_list:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '没有此标签'})
            ser = TagSer(tag_list)
            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": ser.data})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})


# 分类
class ClassIfyView(ViewSet):

    # 添加分类
    @check_login
    def add_classify(self, request):
        name = request.data.get("name")
        classify_id = request.data.get("classify_id")

        try:
            classify = ClassIfyModel.objects.filter(name=name, is_delete=False)
            if classify:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "此分类已经存在"})

            if classify_id:
                classify = ClassIfyModel.objects.filter(id=classify_id, is_delete=False).first()
                if not classify:
                    return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此分类"})

            data = {
                "name": name,
                "classify": classify_id
            }
            ser = ClassifySer(data=data)
            if not ser.is_valid():
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': ser.errors})
            ser.save()
            return Response({"code": status.HTTP_200_OK, "msg": "添加分类成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "服务器错误"})

    # 获取分类
    @check_login
    def list_classify(self, request):
        try:
            list = ClassIfyModel.objects.filter(classify=None, is_delete=False).all()
            list = ClassifySer(list, many=True).data
            list = json.loads(json.dumps(list))
            for i in list:
                classify = ClassIfyModel.objects.filter(is_delete=False, classify=i['id']).all()
                classify = ClassifySer(classify, many=True).data
                classify = json.loads(json.dumps(classify))
                i['classify_list'] = classify

            return Response({"code": status.HTTP_200_OK, "msg": "获取分类成功", "data": list})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "服务器错误"})

    # 修改分类
    @check_login
    def up_classify(self, request, pk):
        name = request.data.get("name")
        classify_id = request.data.get("classify_id")

        try:
            classify = ClassIfyModel.objects.filter(id=pk, is_delete=False)
            if not classify:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有这个分类"})

            classify = ClassIfyModel.objects.filter(name=name, is_delete=False)
            if classify:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "分类名称已经存在"})

            if name:
                classify.update(name=name)
            if classify_id:
                classify.update(classify=classify_id)
            return Response({"code": status.HTTP_200_OK, "msg": "修改分类成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "服务器错误"})

    # 删除分类
    @check_login
    def del_classify(self, request, pk):
        try:
            classify = ClassIfyModel.objects.filter(id=pk, is_delete=False)

            if not classify:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有这个分类"})

            classify.update(is_delete=True)

            return Response({"code": status.HTTP_200_OK, "msg": "删除分类成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "服务器错误"})


# 学习内容
class ContentsView(ViewSet):

    # 添加学习内容
    @check_login
    def add_contents(self, request):
        user_id = self._cuser.id
        title = request.data.get("title")
        content = request.data.get("content")
        intro = request.data.get("intro")
        classify_id = request.data.get("classify_id")
        is_open = request.data.get("is_open")
        tag_id = request.data.get("tag_id")

        if not all([title, content, intro, classify_id, tag_id, is_open]):
            return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "数据不全"})

        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            print("user", user)
            if not user:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此用户"})

            classify = ClassIfyModel.objects.filter(id=classify_id, is_delete=False).first()
            print("classify", classify)
            if not classify:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此分类"})

            tags = TagModel.objects.filter(id=tag_id, is_delete=False, user_id=user_id)
            if not tags:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此标签"})

            contents_list = ContentsModel.objects.filter(title=title, content=content, intro=intro, classify_id=classify, is_delete=False)
            print("---", contents_list)
            if contents_list:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "此学习内容已经存在"})

            ContentsModel.objects.create(title=title, content=content, intro=intro, is_open=is_open, user_id=user_id, classify_id=classify_id)

            contents = ContentsModel.objects.filter(title=title, content=content, intro=intro, is_open=is_open, user_id=user_id, classify_id=classify_id).first()
            print("contents", contents)

            tag_content_tb.objects.create(content_id=contents.id, tag_id=tag_id)

            return Response({"code": status.HTTP_200_OK, "msg": "添加学习内容成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "添加学习内容失败"})

    # 获取学习内容
    @check_login
    def list_contents(self, request):
        user_id = self._cuser.id
        try:
            contents = ContentsModel.objects.filter(user_id=user_id, is_delete=False).all()
            contents = ContentsSer(contents, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg": "获取学习内容成功", "data": contents})

        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取学习内容失败"})

    # 删除学习内容
    @check_login
    def del_contents(self, request, pk):
        user_id = self._cuser.id
        try:
            contents = ContentsModel.objects.filter(id=pk, user_id=user_id, is_delete=False)

            if not contents:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此学习内容"})

            contents.update(is_delete=True)

            return Response({"code": status.HTTP_200_OK, "msg": "删除学习内容成功"})

        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "删除学习内容失败"})

    # 修改学习内容
    @check_login
    def up_contents(self, request, pk):
        user_id = self._cuser.id
        title = request.data.get("title")
        content = request.data.get("content")
        intro = request.data.get("intro")
        is_open = request.data.get("is_open")
        classify_id = request.data.get("classify_id")

        try:
            contents = ContentsModel.objects.filter(id=pk, user_id=user_id, is_delete=False)

            if not contents:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此学习内容"})

            classify = ClassIfyModel.objects.filter(id=classify_id, is_delete=False).first()
            print("classify", classify)
            if not classify:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此标签"})

            contents = ContentsModel.objects.filter(title=title, content=content, intro=intro, classify_id=classify, is_delete=False)
            print("---", contents)
            if contents:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "此学习内容已经存在"})

            if title:
                contents.update(title=title)
            if content:
                contents.update(content=content)
            if intro:
                contents.update(intro=intro)
            if is_open:
                contents.update(is_open=is_open)
            if classify_id:
                contents.update(classify_id=classify_id)
            return Response({"code": status.HTTP_200_OK, "msg": "修改学习内容成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "修改学习内容失败"})

    # 获取一个学习内容
    @check_login
    def one_contents(self, request, pk):
        user_id = self._cuser.id
        try:
            contents = ContentsModel.objects.filter(id=pk, user_id=user_id, is_delete=False).first()
            contents = ContentsSer(contents).data
            return Response({"code": status.HTTP_200_OK, "msg": "获取学习内容成功", "data": contents})

        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取学习内容失败"})

    # 获取一个内容的全部弹幕
    @check_login
    def barrage_contents(self, request, pk):
        user_id = self._cuser.id
        try:
            contents = ContentsModel.objects.filter(id=pk, user_id=user_id, is_delete=False).first()
            contents = ContentsSer(contents).data
            barrage = BarrageModel.objects.filter(contents_id=contents["id"], is_delete=False).all()

            barrage = BarrageSer(barrage, many=True).data
            barrage = json.loads(json.dumps(barrage))
            contents["barrage_list"] = barrage
            return Response({"code": status.HTTP_200_OK, "msg": "获取学习内容的弹幕成功", "data": contents})

        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取学习内容失败"})


# 学习资源
class WealthView(ViewSet):

    # 全部获取资源
    @check_login
    def list_wealth(self, request):
        try:

            wealths = WealthModel.objects.all()
            print("wealths", wealths)

            ser = WealthSer(wealths, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": ser})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 添加学习资源
    @check_login
    def add_wealth(self, request):
        user_id = self._cuser.id
        name = request.data.get("name")
        depict = request.data.get("depict")
        price = request.data.get("price")
        sales = request.data.get("sales")

        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此员工"})

            wealths = WealthModel.objects.filter(name=name, depict=depict, price=price, sales=sales, user_id=user_id, is_delete=False)
            print("wealths", wealths)
            if wealths:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "此资源已经存在"})

            WealthModel.objects.create(name=name, depict=depict, price=price, user_id=user_id, sales=sales)
            return Response({"code": status.HTTP_200_OK, "msg": "添加资源成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 获取我的资源
    @check_login
    def me_wealth(self, request):
        user_id = self._cuser.id
        try:
            wealths = WealthModel.objects.filter(user_id=user_id, is_delete=False)
            print("wealths", wealths)

            ser = WealthSer(wealths, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": ser})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 修改学习资源
    @check_login
    def up_wealth(self, request, pk):
        user_id = self._cuser.id
        name = request.data.get("name")
        depict = request.data.get("depict")
        price = request.data.get("price")

        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此员工"})

            wealth = WealthModel.objects.filter(id=pk, user_id=user_id, is_delete=False)
            if not wealth:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此资源"})

            wealths = WealthModel.objects.filter(name=name, depict=depict, price=price, user_id=user_id, is_delete=False).first()
            print("wealths", wealths)
            if wealths:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "此资源已经存在"})

            if name:
                wealth.update(name=name)
            if depict:
                wealth.update(depict=depict)
            if price:
                wealth.update(price=price)

            return Response({"code": status.HTTP_200_OK, "msg": "修改资源成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 删除我的学习资源
    @check_login
    def del_wealth(self, request, pk):
        user_id = self._cuser.id

        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此员工"})

            wealth = WealthModel.objects.filter(id=pk, user_id=user_id, is_delete=False)
            if not wealth:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此资源"})

            wealth.update(is_delete=True)

            return Response({"code": status.HTTP_200_OK, "msg": "删除资源成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 获取资源详情
    @check_login
    def details_wealth(self, request, pk):
        user_id = self._cuser.id
        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此员工"})

            wealth = WealthModel.objects.filter(id=pk, user_id=user_id, is_delete=False).first()
            if not wealth:
               return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此资源"})
            wealth = WealthSer(wealth).data
            print("wealth", wealth)
            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": wealth})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})



        pass


# 学习任务
class TaskView(ViewSet):

    # 添加学习任务
    @check_login
    def add_task(self, request):
        user_id = self._cuser.id
        content = request.data.get("content")
        classs = request.data.get("classs")

        if not all([content, classs]):
            return Response({{"code": status.HTTP_204_NO_CONTENT, "msg": "数据不全"}})

        try:
            contents = ContentsModel.objects.filter(id=content, is_delete=False)
            if not contents:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此内容"})

            class_list = ClasssModel.objects.filter(id=classs, is_delete=False)
            if not class_list:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此班级"})

            TaskModel.objects.create(content_id=content, classs_id=classs)

            task = TaskModel.objects.filter(content_id=content, classs_id=classs).first()
            print("task", task)
            if not task:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此任务"})
            user = UserModel.objects.filter(classs_id=classs, user=user_id, is_delete=False).all()
            print('user', user)
            user = UserSer(user, many=True).data
            user = json.loads(json.dumps(user))
            for i in user:
                print("i", i)
                RecordModel.objects.create(task_id=task.id, user_id=i["id"], is_state=1, tokinaga=2)
            return Response({"code": status.HTTP_200_OK, "msg": "添加学习任务成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "添加失败"})

    # 获取学习任务
    @check_login
    def list_task(self, request):
        user_id = self._cuser.id

        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})
            user = UserSer(user).data
            print("user", user)

            classs = ClasssModel.objects.filter(id=user["classs"], is_delete=False).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此班级"})
            classs = ClasssSer(classs).data

            task = TaskModel.objects.filter(classs_id=classs["id"], is_delete=False)
            if not task:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此班级的任务"})
            task = TaskSer(task, many=True).data

            return Response({"code": status.HTTP_200_OK, "msg": "查看学习任务成功", "data": task})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "查看失败"})

    # 获取学习任务详情
    @check_login
    def details_task(self, request, pk):
        user_id = self._cuser.id

        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})
            user = UserSer(user).data

            classs = ClasssModel.objects.filter(id=user["classs"], is_delete=False).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此班级"})
            classs = ClasssSer(classs).data

            contents = ContentsModel.objects.filter(id=pk, is_delete=False).first()
            if not contents:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此内容"})
            contents = ContentsSer(contents).data
            contents = json.loads(json.dumps(contents))

            task = TaskModel.objects.filter(classs_id=classs["id"], content_id=contents['id'], is_delete=False).first()
            if not task:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此班级的任务"})

            task = TaskSer(task).data
            task = json.loads(json.dumps(task))

            contents["task_list"] = task
            date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            print("date", date)
            record = RecordModel.objects.filter(id=task["id"], is_delete=False)
            if not record:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此记录"})
            record.update(start_time=date)

            return Response({"code": status.HTTP_200_OK, "msg": "查看学习任务详情成功", "data": contents})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "查看失败"})


# 学习记录
class RecordView(ViewSet):

    # 获取老师下的所有学生的学习记录
    @check_login
    def teacher_record(self, request):
        user_id = self._cuser.id

        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False)
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            user = UserModel.objects.filter(user=user_id, is_delete=False).all()
            user = UserSer(user, many=True).data
            user = json.loads(json.dumps(user))
            print("user", user)
            for i in user:
                print("i", i)
                record = RecordModel.objects.filter(user_id=i["id"], is_delete=False).all()
                record = RecordSer(record, many=True).data
                record = json.loads(json.dumps(record))
                i['record_list'] = record
            # print("recode", record)
            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": user})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 获取全部学习记录
    @check_login
    def list_record(self, request):
        user_id = self._cuser.id
        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            print("user", user)
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            record = RecordModel.objects.filter(user_id=user.id, is_delete=False).all()
            record = RecordSer(record, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": record})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 获取没有完成的学习记录
    @check_login
    def incomplete_record(self, request):
        user_id = self._cuser.id
        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            print("user", user)
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            record = RecordModel.objects.filter(user_id=user.id, is_state=1, is_delete=False).all()
            record = RecordSer(record, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": record})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 获取作弊的学习记录
    @check_login
    def plagiarize_record(self, request):
        user_id = self._cuser.id
        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            print("user", user)
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            record = RecordModel.objects.filter(user_id=user.id, is_state=2, is_delete=False).all()
            record = RecordSer(record, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": record})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 获取完成的学习记录
    @check_login
    def finish_record(self, request):
        user_id = self._cuser.id
        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            print("user", user)
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            record = RecordModel.objects.filter(user_id=user.id, is_state=3, is_delete=False).all()
            record = RecordSer(record, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": record})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 获取费力完成的学习记录
    @check_login
    def strenuosity_record(self, request):
        user_id = self._cuser.id
        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            print("user", user)
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            record = RecordModel.objects.filter(user_id=user.id, is_state=4, is_delete=False).all()
            record = RecordSer(record, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": record})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取失败"})

    # 修改学习状态
    def upd_record(self, request, pk):

        try:
            record = RecordModel.objects.filter(id=pk, is_delete=False).first()
            if not record:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '学习记录不存在'})

            record = RecordSer(record)
            record = json.loads(json.dumps(record.data))

            start_time = record['start_time'].replace('T', ' ')
            finish_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            tokinaga = datetime.datetime.strptime(finish_time, '%Y-%m-%d %H:%M:%S') - datetime.datetime.strptime(
                start_time, '%Y-%m-%d %H:%M:%S')
            print(tokinaga, type(tokinaga))

            record = RecordModel.objects.filter(id=pk, is_delete=False)
            time1 = datetime.timedelta(seconds=86400)  # 24小时
            time2 = datetime.timedelta(seconds=3600)  # 6小时
            time3 = datetime.timedelta(seconds=21600)  # 1小时
            time4 = datetime.timedelta(seconds=1200)  # 20分钟
            if tokinaga >= time1 or tokinaga <= time4:
                print('作弊完成')
                record.update(tokinaga=tokinaga, is_status=2)
            if tokinaga <= time2 and tokinaga > time4:
                print('已完成')
                record.update(tokinaga=tokinaga, is_status=3)
            if tokinaga <= time3 and tokinaga > time2:
                print('费力完成')
                record.update(tokinaga=tokinaga, is_status=4)

            record.update(finish_time=finish_time)

            return Response({'code': status.HTTP_200_OK, 'msg': '修改成功'})


        except Exception as e:
            print("失败", e)
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})


# 评论
class CommentView(ViewSet):

    # 添加评论
    @check_login
    def add_comment(self, request):
        user_id = self._cuser.id
        content = request.data.get("content")
        contents_id = request.data.get("contents_id")

        print(user_id, content, contents_id)

        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            contents = ContentsModel.objects.filter(id=contents_id, is_delete=False).first()
            if not contents:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此学习内容"})

            CommentModel.objects.create(content=content, user_id=user_id, contents_id=contents_id)

            return Response({"code": status.HTTP_200_OK, "msg": "评论成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "评论失败"})

    # 获取学习内容下的评论
    @check_login
    def list_comment(self, request, pk):

        try:
            contents = ContentsModel.objects.filter(id=pk, is_delete=False).first()
            if not contents:
                return Response({"code": status.HTTP_204_NO_CONTENT, "meg": "没有此学习内容"})

            comment = CommentModel.objects.filter(contents_id=contents.id, is_delete=False).all()
            ser = CommentSer(comment, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg": "获取评论成功", "data": ser})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "获取评论失败"})


# 收藏
class CollectView(ViewSet):

    # 添加收藏
    @check_login
    def add_collect(self, request, pk):
        user_id = self._cuser.id
        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            wealth = WealthModel.objects.filter(id=pk, is_delete=False).first()
            if not wealth:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此资源"})

            collect = CollectModel.objects.filter(user_id=user_id, wealth_id=wealth.id, is_delete=False).first()
            if collect:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "此资源已经收藏"})

            collect = CollectModel.objects.filter(user_id=user_id, wealth_id=wealth.id, is_delete=True)
            if collect:
                collect.update(is_delete=False)
            else:
                CollectModel.objects.create(user_id=user_id, wealth_id=wealth.id)

            return Response({"code": status.HTTP_200_OK, "meg": "收藏成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "meg": "收藏失败"})

    # 取消收藏
    @check_login
    def del_collect(self, request, pk):
        user_id = self._cuser.id
        try:

            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            wealth = WealthModel.objects.filter(id=pk, is_delete=False).first()
            if not wealth:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此资源"})

            collect = CollectModel.objects.filter(user_id=user_id, wealth_id=wealth.id, is_delete=False)
            if not collect:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "此资源没有收藏"})
            collect.update(is_delete=True)
            return Response({"code": status.HTTP_200_OK, "meg": "取消收藏成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "meg": "取消收藏失败"})

    # 获取我的收藏
    @check_login
    def me_collect(self, request):
        user_id = self._cuser.id
        try:

            user = UserModel.objects.filter(id=user_id,  is_delete=False)
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "没有此用户"})

            collect = CollectModel.objects.filter(user_id=user_id, is_delete=False).all()
            collect = CollectSer(collect, many=True).data
            print("--", collect)
            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": collect})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})






